package com.example.day9_sqlite;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

public class NetFragment extends Fragment {
    List<MusicEntity.DataBean> musics = new ArrayList<>();
    MusicAdapter musicAdapter;
    private ListView lv;

    public NetFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View inflate = inflater.inflate(R.layout.fragment_net, container, false);
        initView(inflate);
        musicAdapter = new MusicAdapter();
        lv.setAdapter(musicAdapter);

        new MyTask().execute("http://10.161.9.80:7004/song/json?singer=%E9%82%93%E7%B4%AB%E6%A3%8B");

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MusicDao.getInstance(getContext()).insert(musicAdapter.getItem(position));
                Toast.makeText(getContext(), "收藏成功", Toast.LENGTH_SHORT).show();
            }
        });
        return inflate;
    }

    private void initView(View view) {
        lv = (ListView) view.findViewById(R.id.lv);
    }

    class MyTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... strings) {
            return HttpUtils.doGet(strings[0]);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Gson gson = new Gson();
            musicAdapter.addAll(gson.fromJson(s,MusicEntity.class).getData());
        }
    }
}